/**
 *
 * Copyright (C) 2013 陕西威尔伯乐信息技术有限公司
 *
 * @className:com.wellbole.sms.client.impl.SmsSenderImpl
 * @description: 短信发送器默认实现
 *
 * @version:v1.0.0
 * @author:李飞
 *
 * Modification History:
 * Date         Author      Version     Description
 * -----------------------------------------------------------------
 * 2013年7月1日      李飞                       v1.0.0        create
 *
 */
package com.wellbole.sms.client.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wellbole.sms.client.SmsClient;
import com.wellbole.sms.client.SmsSender;
import com.wellbole.sms.client.Version;
import com.wellbole.sms.client.message.OutboundMessage;
import com.wellbole.sms.client.result.SmsSendResult;

/**
 *
 * 短信发送器默认实现
 *
 * @author 李飞
 *
 */
public class SmsSenderImpl extends AbstractOperator implements SmsSender {
	/**
	 * 日志
	 */
	private static final Logger logger = LogManager.getLogger(Thread
			.currentThread().getStackTrace()[2].getClassName());

	static{
		logger.info("SmsEngineClient version:"+Version.VERSION + ",update at:" + Version.LAST_UPDATE_AT);
	}

	/**
	 * 默认构造函数，什么都不做，主要用于Spring集成
	 */
	public SmsSenderImpl() {
		super("1.0", "sms.send");
	}

	/**
	 * 构造函数，主要用于编程方式实现的场合
	 *
	 * @param client
	 *            发送数据客户端接口
	 */
	public SmsSenderImpl(SmsClient client) {
		super("1.0", "sms.send", client);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.lh.sms.client.SmsSender#send(com.lh.sms.client.pojo.OutboundMessage)
	 */
	@SuppressWarnings("static-access")
	public SmsSendResult send(OutboundMessage outboundMessage) {
		// 限制每秒最多发送50条
		try {
			Thread.currentThread().sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 构造参数表
		Map<String, String> parameters = new HashMap<String, String>();
		//设定msgid
		String msgid = outboundMessage.getMsgid();
		if(msgid != null && ! msgid.isEmpty()){
			parameters.put("msgid", msgid);
		}
		parameters.put("phone", outboundMessage.getPhone());
		parameters.put("content", outboundMessage.getContent());
		parameters.put("sendAt", dateToStr(outboundMessage.getSendAt()));
		parameters.put("extCode", outboundMessage.getExtCode());

		// 发送请求，执行结果
		String responseStr = client.execute(version, methodName, parameters);

		// 打印原始值
		logger.debug(responseStr);

		// 根据响应内容构建发送结果
		return createResultFromResponse(responseStr);
	}

	/**
	 * 根据响应内容构建发送结果
	 *
	 * @param responseStr
	 *            执行结果
	 * @return 发送结果
	 */
	private SmsSendResult createResultFromResponse(String responseStr) {
		SmsSendResult result = null;
		JSONObject jsonObject = null;
		try {
			jsonObject = JSON.parseObject(responseStr);
		} catch (Exception e) {
			result = SmsSendResult.createSrrHasError(responseStr);
			return result;
		}
		if (jsonObject.containsKey("code")) {
			result = SmsSendResult.createSrrHasError(jsonObject
					.getString("message"));
		} else {
			int resultCode = jsonObject.getInteger("resultCode");
			if (0 == resultCode) {
				result = SmsSendResult.createSrrHasData(jsonObject
						.getString("msgid"));
			} else {
				result = SmsSendResult.createSrrHasError(jsonObject
						.getString("errorMessage"));
			}
		}
		return result;
	}
}
